package com.example.demo.utils.exportUtils;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;


import org.apache.commons.lang3.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author liyanhua@gogpay.cn
 * @date 2023/11/28 8:57
 */
@Component
public class EasyExcelUtils {

    private final static Logger log = LoggerFactory.getLogger(EasyExcelUtils.class);

    // /**
    //  * 注入多多资源中心文件上传
    //  */
    // private final AssetsClient assetsClient;

    /**
     * 每个sheet的容量，即超过60000时就会把数据分sheet
     */
    private static final int PAGE_SIZE = 60000;



    /**
     * 导出报表(使用注解方式设置Excel头数据) *
     *
     * @param data           报表数据
     * @param excelClass     报表实体类的Class（根据该Class的属性来设置Excel的头属性）
     * @param exportPassword 密码
     * @return url
     */
    public String exportByExcel(List<?> data, Class<?> excelClass, String exportPassword) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        long exportStartTime = System.currentTimeMillis();

        log.info("报表导出Size: " + data.size() + "条。");

        // 把查询到的数据按设置的sheet的容量进行切割
        List<? extends List<?>> lists = SplitList.splitList(data, PAGE_SIZE);
        ExcelWriterBuilder excelWriterBuilder = EasyExcel
                .write(os, excelClass)
                .inMemory(true)
                .registerWriteHandler(DcbEasyExcel.formatExcel());
        if (StringUtils.isNotEmpty(exportPassword)) {
            excelWriterBuilder.password(exportPassword);
        }
        ExcelWriter excelWriter = excelWriterBuilder.build();

        // 浏览器访问url直接下载文件的方式
        ExcelWriterSheetBuilder excelWriterSheetBuilder;
        WriteSheet writeSheet;
        for (int i = 1; i <= lists.size(); ++i) {
            excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
            excelWriterSheetBuilder.sheetNo(i).sheetName("sheet" + i);
            //设置水印
            // excelWriterSheetBuilder.sheetNo(i).registerWriteHandler(new CardRecordWaterMarkHandler());
            writeSheet = excelWriterSheetBuilder.build();
            excelWriter.write(lists.get(i - 1), writeSheet);
        }
        // 必须要finish才会写入，不finish只会创建empty的文件
        excelWriter.finish();
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);

        MultipartFile multipartFile = new MockMultipartFile(".xlsx", ".xlsx", "xlsx", is);

        System.out.println("报表导出结束时间:" + new Date() + ";导出耗时: " + (System.currentTimeMillis() - exportStartTime) + "ms");
        // return this.upload(multipartFile, null, null);
        // 返回文件地址
        return "";
    }

    // /**
    //  * 上传文件
    //  *
    //  * @param multipartFile  上传的文件
    //  * @param formatFileName 文件名称
    //  * @param uploadAppName  自定义的文件夹名称
    //  * @return url--上传到oss后的资源地址
    //  */
    // public String upload(MultipartFile multipartFile, String formatFileName, String uploadAppName) {
    //     if (null == multipartFile) {
    //         throw new ServiceException("文件为空！请检查！");
    //     }
    //
    //     String url = null;
    //     log.info("===========开始上传文件============");
    //
    //     AssetsForm assetsForm = new AssetsForm();
    //     assetsForm.setFile(multipartFile);
    //     if (StringUtils.isNotEmpty(uploadAppName)) {
    //         assetsForm.setDirectory(uploadAppName);
    //     }
    //     if (StringUtils.isNotEmpty(formatFileName)) {
    //         assetsForm.setFilename(formatFileName);
    //     }
    //
    //     try {
    //         ResponseResult<AssetsResult> responseResult = assetsClient.fileUpload(assetsForm);
    //         log.info("==========上传返回结果：{}===========", JSON.toJSONString(responseResult));
    //         if (null == responseResult) {
    //             log.warn("=======上传返回结果为空！=======");
    //             throw new ServiceException("上传结果返回为空！");
    //         }
    //         if (ResultCode.SUCCESS_CODE != responseResult.getStatus()) {
    //             log.warn("=======上传失败，原因：{}=======", responseResult.getMsg());
    //             throw new ServiceException(responseResult.getMsg());
    //         }
    //         url = responseResult.getData().getPublicUrl();
    //     } catch (Exception e) {
    //         log.error("=========调用多多资源中心上传文件失败，原因：{}=========", e.getMessage());
    //         throw new ServiceException("上传文件失败！");
    //     }
    //     return url;
    // }
}
